package com.ifacebox.web.admin.master.controller;

import com.ifacebox.web.admin.controller.BaseBodyController;
import com.ifacebox.web.admin.master.model.*;
import com.ifacebox.web.admin.master.service.MasterQuartzService;
import com.ifacebox.web.admin.master.service.MasterUserService;
import com.ifacebox.web.common.annotation.UserAgentRequest;
import com.ifacebox.web.common.model.BaseResponse;
import com.ifacebox.web.common.model.ModelResponse;
import com.ifacebox.web.common.model.StatusResponse;
import com.ifacebox.web.common.model.UserAgent;
import org.quartz.Trigger;
import org.quartz.TriggerUtils;
import org.quartz.impl.triggers.CronTriggerImpl;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @author znn
 */
@Controller
public class MasterQuartzController extends BaseBodyController {
    @Resource
    private MasterQuartzService masterQuartzService;

    @GetMapping("/admin/quartz/run.json")
    @ResponseBody
    public ModelResponse<List<Date>> run(String cron) {
        if (!masterQuartzService.isValidExpression(cron)) {
            return new ModelResponse<>(StatusResponse.VALID_FAIL, "任务表达式不正确！");
        }
        try {
            CronTriggerImpl cronTriggerImpl = new CronTriggerImpl();
            cronTriggerImpl.setCronExpression(cron);
            return new ModelResponse<>(StatusResponse.SUCCESS, TriggerUtils.computeFireTimes(cronTriggerImpl, null, 10));
        } catch (Exception e) {
            return new ModelResponse<>(StatusResponse.EXCEPTION, e.getMessage());
        }
    }

    @GetMapping("/admin/quartz/status.json")
    @ResponseBody
    public ModelResponse<Trigger.TriggerState[]> status() {
        return new ModelResponse<>(StatusResponse.SUCCESS, Trigger.TriggerState.values());
    }

    @GetMapping("/admin/quartz/list.json")
    @ResponseBody
    public ModelResponse<List<MasterQuartz>> list(@UserAgentRequest UserAgent userAgent, MasterQuartzQuery masterQuartzQuery) {
        if (!permissionManager.hasPermission(userAgent)) {
            return new ModelResponse<>(StatusResponse.LOGOUT);
        }
        MasterUser masterUser = userAgent.getMasterUser();
        if (!MasterUserService.ADMIN_NAME.equals(masterUser.getUsername())) {
            masterQuartzQuery.setCreateUser(masterUser.getUsername());
        }
        return new ModelResponse<>(StatusResponse.SUCCESS, masterQuartzService.total(masterQuartzQuery), masterQuartzService.query(masterQuartzQuery));
    }

    @PostMapping("/admin/quartz/save.json")
    @ResponseBody
    public BaseResponse save(@UserAgentRequest UserAgent userAgent, @RequestBody @Validated MasterQuartz masterQuartz) {
        if (!permissionManager.hasPermission(userAgent)) {
            return new BaseResponse(StatusResponse.LOGOUT);
        }
        if (!masterQuartzService.isValidClassName(masterQuartz.getClassName())) {
            return new BaseResponse(StatusResponse.SAVE_FAIL, "任务类名不正确！");
        }
        if (!masterQuartzService.isValidExpression(masterQuartz.getCronExpression())) {
            return new BaseResponse(StatusResponse.SAVE_FAIL, "任务表达式不正确！");
        }
        if (!masterQuartzService.save(masterQuartz, userAgent)) {
            return new BaseResponse(StatusResponse.SAVE_FAIL);
        }
        traceLoggerService.addTraceLogger(userAgent, "添加定时任务成功！【{}】", masterQuartz.toString());
        return new BaseResponse(StatusResponse.SUCCESS);
    }

    @PutMapping("/admin/quartz/edit.json")
    @ResponseBody
    public BaseResponse edit(@UserAgentRequest UserAgent userAgent, @RequestBody @Validated MasterQuartz masterQuartz) {
        if (!permissionManager.hasPermission(userAgent)) {
            return new BaseResponse(StatusResponse.LOGOUT);
        }
        MasterQuartz oldMasterQuartz = masterQuartzService.queryById(masterQuartz.getId());
        if (ObjectUtils.isEmpty(oldMasterQuartz)) {
            return new BaseResponse(StatusResponse.UPDATE_FAIL, "修改的定时任务不存在！");
        }
        if (!oldMasterQuartz.getClassName().equals(masterQuartz.getClassName())) {
            return new BaseResponse(StatusResponse.UPDATE_FAIL, "任务类名不能修改！");
        }
        if (!masterQuartzService.isValidClassName(masterQuartz.getClassName())) {
            return new BaseResponse(StatusResponse.UPDATE_FAIL, "任务类名不正确！");
        }
        if (!masterQuartzService.isValidExpression(masterQuartz.getCronExpression())) {
            return new BaseResponse(StatusResponse.UPDATE_FAIL, "任务表达式不正确！");
        }
        masterQuartz.setJobKey(oldMasterQuartz.getJobKey());
        if (!masterQuartzService.checkExists(masterQuartz)) {
            return new BaseResponse(StatusResponse.UPDATE_FAIL, "定时任务已完成或者不存在！");
        }
        if (!masterQuartzService.edit(masterQuartz, userAgent)) {
            return new BaseResponse(StatusResponse.UPDATE_FAIL);
        }
        traceLoggerService.addTraceLogger(userAgent, "修改定时任务成功！【{}】", masterQuartz.toString());
        return new BaseResponse(StatusResponse.SUCCESS);
    }

    @DeleteMapping("/admin/quartz/delete.json")
    @ResponseBody
    public BaseResponse delete(@UserAgentRequest UserAgent userAgent, @RequestParam Integer id) {
        if (!permissionManager.hasPermission(userAgent)) {
            return new BaseResponse(StatusResponse.LOGOUT);
        }
        MasterQuartz masterQuartz = masterQuartzService.queryById(id);
        if (ObjectUtils.isEmpty(masterQuartz)) {
            return new BaseResponse(StatusResponse.DELETE_FAIL, "删除的定时任务不存在！");
        }
        if (!masterQuartzService.delete(masterQuartz)) {
            return new BaseResponse(StatusResponse.DELETE_FAIL);
        }
        traceLoggerService.addTraceLogger(userAgent, "删除定时任务成功！【{}】", masterQuartz.toString());
        return new BaseResponse(StatusResponse.SUCCESS);
    }

    @GetMapping("/admin/quartz/resume.json")
    @ResponseBody
    public BaseResponse resume(@UserAgentRequest UserAgent userAgent, @RequestParam Integer id) {
        if (!permissionManager.hasPermission(userAgent)) {
            return new BaseResponse(StatusResponse.LOGOUT);
        }
        MasterQuartz masterQuartz = masterQuartzService.queryById(id);
        if (ObjectUtils.isEmpty(masterQuartz)) {
            return new BaseResponse(StatusResponse.UPDATE_FAIL, "定时任务不存在！");
        }
        if (!masterQuartzService.checkExists(masterQuartz)) {
            return new BaseResponse(StatusResponse.UPDATE_FAIL, "定时任务已完成或者不存在！");
        }
        if (!masterQuartzService.resumeJob(masterQuartz)) {
            return new BaseResponse(StatusResponse.UPDATE_FAIL);
        }
        traceLoggerService.addTraceLogger(userAgent, "恢复定时任务成功！【{}】", masterQuartz.toString());
        return new BaseResponse(StatusResponse.SUCCESS);
    }

    @GetMapping("/admin/quartz/pause.json")
    @ResponseBody
    public BaseResponse pause(@UserAgentRequest UserAgent userAgent, @RequestParam Integer id) {
        if (!permissionManager.hasPermission(userAgent)) {
            return new BaseResponse(StatusResponse.LOGOUT);
        }
        MasterQuartz masterQuartz = masterQuartzService.queryById(id);
        if (ObjectUtils.isEmpty(masterQuartz)) {
            return new BaseResponse(StatusResponse.UPDATE_FAIL, "定时任务不存在！");
        }
        if (!masterQuartzService.checkExists(masterQuartz)) {
            return new BaseResponse(StatusResponse.UPDATE_FAIL, "定时任务已完成或者不存在！");
        }
        if (!masterQuartzService.pauseJob(masterQuartz)) {
            return new BaseResponse(StatusResponse.UPDATE_FAIL);
        }
        traceLoggerService.addTraceLogger(userAgent, "暂停定时任务成功！【{}】", masterQuartz.toString());
        return new BaseResponse(StatusResponse.SUCCESS);
    }
}
